package com.dudu.service.support;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.dudu.bean.IfControlBean;
import com.dudu.bean.IfControlCheckConclusionPushBean;
import com.dudu.bean.IfControlRuleBean;
import com.dudu.bean.InfoControlAccountBean;
import com.dudu.dao.InfoControlDao;
import com.dudu.service.IInfoControl;
import com.dudu.service.impl.InfoControlServiceImpl;
import com.dudu.utils.DictionaryUtils;
import com.dudu.utils.Encrypt;
import com.dudu.utils.HttpRequest;

import net.sf.json.JSONObject;

/**
 * 语音类信控服务实现类
 * 
 * @author zx
 *
 */
public class VoiceInfoControlProcessor extends AbstractInfoControlProcessor {

	/*
	 * 语音请求url
	 */
	private static final String VOICE_URL;

	/*
	 * 短信发送url
	 */
	private static final String SMS_URL;

	/*
	 * 系统账户，用来发送语音通知和短信
	 */
	private static InfoControlAccountBean SYSTEM_ACCOUNT;

	/*
	 * 短信模板编号
	 */
	private String smsTemplate;

	/**
	 * 初始化
	 */
	static {
		String domainUrl = DictionaryUtils.getValueByTypeAndKey("common", "domainUrl");
		VOICE_URL = domainUrl + "/VOICE/sendVoiceNoticeByVoiceId.do";
		SMS_URL = domainUrl + "/SMSv4/postSms.do";
		String accountInfo = "{" + DictionaryUtils.getValueByTypeAndKey("infoControl", "accountInfo") + "}";
		SYSTEM_ACCOUNT = (InfoControlAccountBean) JSONObject.toBean(JSONObject.fromObject(accountInfo),
				InfoControlAccountBean.class);
		String requestTimeStamp = String.valueOf(new Date().getTime());
		String sign = Encrypt
				.sha1Encrypt(SYSTEM_ACCOUNT.getCust_account() + SYSTEM_ACCOUNT.getKey_private() + requestTimeStamp);
		SYSTEM_ACCOUNT.setSign(sign);
		SYSTEM_ACCOUNT.setTimestamp(requestTimeStamp);
	}

	/**
	 * 构造函数
	 * 
	 * @param ifcBean
	 * @param ifcRules
	 * @param parameterMap
	 */
	public VoiceInfoControlProcessor(IfControlBean ifcBean, List<IfControlRuleBean> ifcRules,
			Map<String, String> parameterMap) {
		super(ifcBean, ifcRules, parameterMap);
		this.smsTemplate = DictionaryUtils.getValueByTypeAndKey("infoControl", "infocontrolSmsTemplate");
	}

	@Override
	public int alreadyRequestCount(IfControlBean requestBean) {
		InfoControlDao icDao = new InfoControlDao();
		return icDao.querySendNoticeCountByBatchNumber(requestBean, "-1");
	}

	@Override
	public void ifControlProcess(IfControlBean ifcBean, IfControlRuleBean rule, boolean startedIfControl) {
		InfoControlDao icDao = new InfoControlDao();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date newScheduleDate = new Date(new Date().getTime() + rule.getCheckPeriod() * 60 * 1000);
		String newScheduleSendTime = format.format(newScheduleDate);
		int updateCount = icDao.updateNoticeStatusAndScheduletime(ifcBean, "2", newScheduleSendTime);// 更新语音通知状态和超时发送时间
		/** 没有进入信控状态 **/
		if (!startedIfControl) {
			int id = icDao.startInfoControl(ifcBean, rule);
			if (id != -1 && updateCount > 0) {
				ifcBean.setId(id);// 更新前导音
				sendVoiceAudition(ifcBean, rule, SYSTEM_ACCOUNT);
				sendSmsMessage(ifcBean, rule, SYSTEM_ACCOUNT);
			}
		}
	}

	/**
	 * 发送短信给信控核查人员
	 * 
	 * @param requestBean
	 *            请求数据
	 * @param rule
	 *            命中的规则
	 * @param account
	 *            系统账户
	 */
	private void sendSmsMessage(IfControlBean requestBean, IfControlRuleBean rule, InfoControlAccountBean account) {
		String checkNumbers = rule.getCheckNumbers();// 所有核查人号码
		String ext_terminalCode = checkNumbers.split(",")[0];// 默认第一个号码为id
		StringBuffer parameter = new StringBuffer();
		parameter.append("app_key=").append(account.getApp_key());
		parameter.append("&cust_account=").append(account.getCust_account());
		parameter.append("&timestamp=").append(account.getTimestamp());
		parameter.append("&sign=").append(account.getSign());
		parameter.append("&called=").append(checkNumbers);
		parameter.append("&msg_id=").append(requestBean.getId());
		parameter.append("&template_code=").append(smsTemplate);
		parameter.append("&template_params=[\"").append(rule.getCheckPeriod()).append("\"]");
		parameter.append("&ext_terminalCode=").append(ext_terminalCode).append("&up_sms=1");
		HttpRequest.post(SMS_URL, parameter);
	}

	/**
	 * 取消语音通知的发送
	 * 
	 * @return
	 */
	private int cancelSendNotice(IfControlBean controlBean) {
		InfoControlDao icDao = new InfoControlDao();
		return icDao.cancelSendNotice(controlBean);
	}

	/**
	 * 发送试听语音通知给审核人员,此处调用的是重发接口
	 * 
	 * @param ifcBean
	 * @param rule
	 * @param account
	 */
	private void sendVoiceAudition(IfControlBean ifcBean, IfControlRuleBean rule, InfoControlAccountBean account) {
		String checkNumbers = rule.getCheckNumbers();// 所有核查人号码
		String caller = checkNumbers.split(",")[0];// 默认第一个号码为主叫
		String ext_terminalCode = caller;// 用户id默认为第一个手机号码
		String custAccount = account.getCust_account();// 从配置取
		StringBuffer parameter = new StringBuffer();
		parameter.append("app_key=").append(account.getApp_key());
		parameter.append("&cust_account=").append(custAccount);
		parameter.append("&timestamp=").append(account.getTimestamp()).append("&sign=").append(account.getSign());
		parameter.append("&caller=").append(caller).append("&ext_terminalCode=").append(ext_terminalCode);
		parameter.append("&called=").append(checkNumbers);
		parameter.append("&voice_id=").append(parameterMap.get("voice_id"));
		HttpRequest.post(VOICE_URL, parameter);
	}

	/**
	 * 根据审核员返回的审核结果进行后续处理
	 */
	@Override
	public void postProcess() {
		log.info("接收到短信反馈，反馈内容为" + ifcBean);
		IfControlBean controlBean = ifDao.queryIfControlById(ifcBean);
		if (controlBean != null) {
			IfControlRuleBean ruleBean = controlBean.getRule();
			String checkers = ruleBean.getCheckNumbers();
			String checker = ifcBean.getChecker();
			if (!StringUtils.isEmpty(checkers) && checkers.indexOf(checker) > -1) {
				String checkConclusion = ifcBean.getCheckConclusion();
				if ("Y".equalsIgnoreCase(checkConclusion)) {
					ifDao.finishIfControlProcess(ifcBean);
				} else if ("N".equalsIgnoreCase(checkConclusion)) {
					// 推送短息校验结果
					ifDao.finishIfControlProcess(ifcBean);
					cancelSendNotice(controlBean);
					IInfoControl service = new InfoControlServiceImpl();
					String url = service.queryIfControlPushURL(controlBean.getAppKey(), controlBean.getCustAccount());
					if (!StringUtils.isEmpty(url)) {
						/**
						 * 插入待核查结果推送表
						 */
						IfControlCheckConclusionPushBean bean = new IfControlCheckConclusionPushBean();
						bean.setHistory_id(ifcBean.getHistroy_id());
						bean.setBatch_number(controlBean.getBatchNumber());
						bean.setCheckconclusion("N");// 审核结论为不通过
						bean.setPush_count(0);// 推送次数
						bean.setStatus("0");// 待发送
						bean.setPush_url(url);
						service.addIfControlCheckConclusionPushInfo(bean);
					}
				} else {
					/**
					 * 其他未知结论
					 */
					log.error("未知的结论" + checkConclusion);
				}
			} else {
				/**
				 * 反馈号码与信控下发号码不匹配
				 */
				log.error("反馈号码与信控下发号码不匹配，发送的号码为" + checkers + ",回复短信的号码为" + checker);
			}
		} else {
			/**
			 * 未找到匹配的信控记录
			 */
			log.error("未找到匹配的信控记录");
		}
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		StringBuffer parameter = new StringBuffer();
		parameter.append("app_key=00F57953494DB1429E31332C4BAD5AB5");
		parameter.append("&cust_account=test1981");
		parameter.append("&timestamp=20160504163328").append("&sign=08c4ba0bf6f147bec77158a3832b0c35324994a6");
		parameter.append("&called=17001090132,13439299392");
		parameter.append("&msg_id=111");
		parameter.append("&template_code=template_infocontrol_01");
		parameter.append("&template_params=[\"5\"]");
		parameter.append("&ext_terminalCode=1982");
		String rs = HttpRequest.post("http://123.103.9.208:7061/SMSv4/postSms.do", parameter);
		System.out.println(new String(rs.getBytes("iso-8859-1"), "utf-8"));
	}

}
